package com.cyp.school.controller;

import com.cyp.school.dto.BlogDTO;
import com.cyp.school.dto.Result;
import com.cyp.school.entity.Blog;
import com.cyp.school.entity.User;
import com.cyp.school.service.BlogService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/blog")
public class BlogController {
    
    @Resource
    private BlogService blogService;
    
    @PostMapping
    public Result<Blog> publishBlog(@RequestParam("title") String title,
                                  @RequestParam("content") String content,
                                  @RequestParam(value = "files", required = false) MultipartFile[] files,
                                  HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        
        Blog blog = new Blog();
        blog.setUserId(user.getId());
        blog.setTitle(title);
        blog.setContent(content);
        
        // 处理多图片上传
        if (files != null && files.length > 0) {
            List<String> imagePaths = new ArrayList<>();
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    try {
                        String fileName = file.getOriginalFilename();
                        String suffixName = fileName.substring(fileName.lastIndexOf("."));
                        String newFileName = UUID.randomUUID().toString() + suffixName;
                        String uploadDir = System.getProperty("user.dir") + "/src/main/resources/static/upload/blog/";
                        File dir = new File(uploadDir);
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        File dest = new File(dir.getAbsolutePath() + File.separator + newFileName);
                        file.transferTo(dest);
                        imagePaths.add("/static/upload/blog/" + newFileName);
                    } catch (IOException e) {
                        return Result.error("图片上传失败: " + e.getMessage());
                    }
                }
            }
            blog.setImages(String.join(",", imagePaths));
        }
        
        return blogService.publishBlog(blog);
    }
    
    @GetMapping("/{id}")
    public Result<BlogDTO> getBlogById(@PathVariable Integer id) {
        return blogService.getBlogById(id);
    }
    
    @GetMapping("/list")
    public Result<List<BlogDTO>> getAllBlogs() {
        return blogService.getAllBlogs();
    }
    
    @GetMapping("/user/{userId}")
    public Result<List<BlogDTO>> getUserBlogs(@PathVariable Integer userId) {
        return blogService.getUserBlogs(userId);
    }
    
    @GetMapping("/my")
    public Result<List<BlogDTO>> getMyBlogs(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        return blogService.getUserBlogs(user.getId());
    }
    
    @PostMapping("/like/{id}")
    public Result<Boolean> likeBlog(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        return blogService.likeBlog(id, user.getId());
    }
    
    @DeleteMapping("/like/{id}")
    public Result<Boolean> unlikeBlog(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        return blogService.unlikeBlog(id, user.getId());
    }
    
    @GetMapping("/like/status/{id}")
    public Result<Boolean> getLikeStatus(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        return blogService.getLikeStatus(id, user.getId());
    }
    
    @PutMapping
    public Result<Blog> updateBlog(@RequestBody Blog blog, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }

//         验证是否为博客作者或管理员
        BlogDTO existBlog = blogService.getBlogById(blog.getId()).getData();
        if (existBlog == null) {
            return Result.error("博客不存在");
        }

        if (!existBlog.getUserId().equals(user.getId()) && user.getRole() != 1) {
            return Result.error(403, "无权限");
        }

        return blogService.updateBlog(blog);
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteBlog(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        
        // 验证是否为博客作者或管理员
        BlogDTO blog = blogService.getBlogById(id).getData();
        if (blog == null) {
            return Result.error("博客不存在");
        }
        
        if (!blog.getUserId().equals(user.getId()) && user.getRole() != 1) {
            return Result.error(403, "无权限");
        }
        
        return blogService.deleteBlog(id);
    }

    @GetMapping("/comment/count")
    public Result<Integer> getCommentCount(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "未登录");
        }
        
        int commentCount = blogService.getCommentCountByUserId(user.getId());
        return Result.success(commentCount);
    }
} 